﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：吕海乐 
    //
    // 文件名：PurchaseOrderUpdate.cs
        // 文件功能描述：采购单维护,添加、删除采购单明细，提交采购明细
    // 创建标识：吕海乐2009-05-13
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using System.Collections.Generic;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Hospitals.Procurement
{
    public partial class PurchaseOrderUpdate : BasePage
    {
        public PurchaseOrderUpdate()
        {
            this.ModuleNo = Module.采购单管理.ToString();
        }

        IBLL_Purchase ip = Factory.BLL_Purchase();
        IBLL_Distribution id = Factory.BLL_Distribution();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HZ.DrugTrade.Web.Function.IsThreeLevel())//项目查询条件仅三级医院可见
            {
                this.ddlProjectid.Visible = false;
                this.lblProjectid.Visible = false;
            }
            //绑定采购单基本信息
            if (!IsPostBack)
            {
                SetBind();
                SetAllBind();
            }
        }

        /// <summary>
        /// 绑定采购单信息
        /// </summary>
        private void SetBind()
        {
            string orderId = Request.QueryString["OrderID"];
            int totalCount = 0;
            IList<Model.View.PurchaseOrder> purchaseOrders = ip.GetPurchaseOrderByWhere(new HZ.DrugTrade.Model.Query.PurchaseOrder() { OrderID = orderId, SortFields = "PlanTime DESC" }, 1, 0, out totalCount);
            if (purchaseOrders.Count > 0)
            {
                Model.View.PurchaseOrder purchaseOrder = ip.GetPurchaseOrderByWhere(new HZ.DrugTrade.Model.Query.PurchaseOrder() { OrderID = orderId, SortFields = "PlanTime DESC" }, 1, 0, out totalCount)[0];
                txtAmount.Text = purchaseOrder.TotalAmount.ToString();
                lblPurseOrder.Text = purchaseOrder.OrderName;
                txtPerson.Text = purchaseOrder.PlanPerson;
                lblReadme.Text = purchaseOrder.Remarks;
                string status = purchaseOrder.OrderStatus.ToString();
                if (status == "0")
                {
                    txtStatus.Text = "未提交";
                    ViewState["status"] = "0";
                }
                else if (status == "1")
                {
                    txtStatus.Text = "已提交";
                    btnAdd.Visible = false;
                    btnDel.Visible = false;
                    btnModCnt.Visible = false;
                    btnSubmit.Visible = false;
                    gvwPurchaseOrderDetail.Columns[gvwPurchaseOrderDetail.Columns.Count - 1].Visible = false;
                    btnDelOrder.Visible = false;
                    ViewState["status"] = "1";
                }
                ViewState["orderID"] = orderId;
            }
            else
            {
                PageError("采购单已被删除！", "PurchaseOrderUnCheck.aspx");
            }
        }

        /// <summary>
        /// 绑定所有符合条件的采购单明细
        /// </summary>
        private void SetAllBind()
        {
            string orderId = Request.QueryString["OrderID"];
            Model.Query.PurchaseOrderDetail qPurchaseOrderDetail = new HZ.DrugTrade.Model.Query.PurchaseOrderDetail();
            qPurchaseOrderDetail.OrderID = orderId;
            qPurchaseOrderDetail.GoodsName = txtGoodsName.Text.Trim();
            qPurchaseOrderDetail.Outlookc = txtOutLookc.Text.Trim();
            //qPurchaseOrderDetail.PinyinCode = this.txtPinyinCode.Text.Trim();
            qPurchaseOrderDetail.CompanyName_SC = txtCompany_SC.Text.Trim();
            qPurchaseOrderDetail.CompanyName_PS = txtCompany_PS.Text.Trim();
            qPurchaseOrderDetail.Unit = txtUnit.Text.Trim();
            //qPurchaseOrderDetail.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                qPurchaseOrderDetail.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                qPurchaseOrderDetail.ProjectID = "0001";
            }
            //if (!string.IsNullOrEmpty(txtPriceFrom.Text.Trim()))
            //{
            //    qPurchaseOrderDetail.PriceFrom = Convert.ToDecimal(txtPriceFrom.Text.Trim());
            //}
            //if (!string.IsNullOrEmpty(txtPriceTo.Text.Trim()))
            //{
            //    qPurchaseOrderDetail.PriceTo = Convert.ToDecimal(txtPriceTo.Text.Trim());
            //}
            qPurchaseOrderDetail.SortFields = "executetime asc";
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount = 0;
            IList<Model.View.PurchaseOrderDetail> purchaseOrderDetailList = ip.GetPurchaseOrderDetailByWhere(qPurchaseOrderDetail, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            AspNetPager1.RecordCount = totalCount;
            gvwPurchaseOrderDetail.PageSize = AspNetPager1.PageSize;
            gvwPurchaseOrderDetail.DataSource = purchaseOrderDetailList;
            gvwPurchaseOrderDetail.DataBind();
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            SetAllBind();
        }

        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnModCnt_Click(object sender, EventArgs e)
        {
            List<PurchaseOrderDetail> myList = new List<PurchaseOrderDetail>();
            for (int i = 0; i < gvwPurchaseOrderDetail.Rows.Count; i++)
            {
                System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwPurchaseOrderDetail.Rows[i].FindControl("checkbox1");
                TextBox txtPurchaseCount = (TextBox)gvwPurchaseOrderDetail.Rows[i].FindControl("txtCount");
                Label lblPrcie = (Label)gvwPurchaseOrderDetail.Rows[i].FindControl("lblPrice");
                if (chk.Checked == true)
                {
                    //采购数量不能为空
                    if (string.IsNullOrEmpty(txtPurchaseCount.Text.Trim()))
                    {
                        HZ.Web.WebUtil.Alert("采购数量不能为空！", this);
                        txtPurchaseCount.Focus();
                        return;
                    }

                    //输入的采购数量为非法字符
                    if ((new HZ.Common.ConvertHelper(txtPurchaseCount.Text.Trim()).ToInt32) == null)
                    {
                        HZ.Web.WebUtil.Alert("输入的采购数量为非法字符！", this);
                        txtPurchaseCount.Focus();
                        return;
                    }

                    //采购数量不能为“0”
                    if ((new HZ.Common.ConvertHelper(txtPurchaseCount.Text.Trim()).ToInt32) == 0)
                    {
                        HZ.Web.WebUtil.Alert("采购数量不能为0！", this);
                        txtPurchaseCount.Focus();
                        return;
                    }

                    if (!string.IsNullOrEmpty(txtPurchaseCount.Text.Trim()) && !string.IsNullOrEmpty(lblPrcie.Text.Trim()))
                    {
                        PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();
                        purchaseOrderDetail.OrderID = Request.QueryString["orderID"];
                        purchaseOrderDetail.Price = new HZ.Common.ConvertHelper(lblPrcie.Text).ToDecimal;
                        purchaseOrderDetail.ProcureCatalogID = gvwPurchaseOrderDetail.DataKeys[i].Values[0].ToString();
                        purchaseOrderDetail.PurchaseCount = new HZ.Common.ConvertHelper(txtPurchaseCount.Text.Trim()).ToInt32;
                        purchaseOrderDetail.Amount = purchaseOrderDetail.Price * purchaseOrderDetail.PurchaseCount;
                        purchaseOrderDetail.CompanyID_PS = gvwPurchaseOrderDetail.DataKeys[i].Values[1].ToString();
                        purchaseOrderDetail.OrderDetailID = gvwPurchaseOrderDetail.DataKeys[i].Values[2].ToString();
                        myList.Add(purchaseOrderDetail);
                    }
                    else
                    {
                        HZ.Web.WebUtil.Alert("采购数量或采购价格不能为空！", this);
                        txtPurchaseCount.Focus();
                        return;
                    }
                }
            }

            int flag = ip.UpdatePurchaseOrderDetail_PurchaseCount_Batch(myList);
            if (flag == 1)
            {
                SetBind();
                SetAllBind();
            }
            else
            {
                PageError("更新失败！", "");
            }
        }

        /// <summary>
        /// 批量删除采购单明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDel_Click(object sender, EventArgs e)
        {
            List<PurchaseOrderDetail> myList = new List<PurchaseOrderDetail>();
            for (int i = 0; i < gvwPurchaseOrderDetail.Rows.Count; i++)
            {
                System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwPurchaseOrderDetail.Rows[i].FindControl("checkbox1");
                if (chk.Checked == true)
                {
                    PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();
                    purchaseOrderDetail.OrderDetailID = gvwPurchaseOrderDetail.DataKeys[i].Values[2].ToString();
                    myList.Add(purchaseOrderDetail);
                }
            }

            int flag = ip.DeletePurchaseOrderDetail_Batch(myList);
            if (flag == 1)
            {
                SetBind();
                SetAllBind();
            }
            else if (flag == 2)
            {
                PageError("采购单已提交或已删除！", "");
            }
            else if (flag == 3)
            {
                PageError("采购单已被删除！", "PurchaseOrderUnCheck.aspx");
            }
            else
            {
                PageError("删除失败！", "");
            }
        }

        /// <summary>
        /// 新增采购单明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            // HZ.Web.WebUtil.RedirectByScript("PurchaseOrderDetailAdd.aspx?flag="+'1'+"&orderID=" + ViewState["orderID"]);
            HZ.Web.WebUtil.RedirectByScript("PurchaseOrderDetailAdd.aspx?orderID=" + ViewState["orderID"]);
        }

        /// <summary>
        /// 绑定审核状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwPurchaseOrderDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Literal ltlOrderDetailState = e.Row.FindControl("ltlOrderDetailState") as Literal;
                TextBox txtCount = e.Row.FindControl("txtCount") as TextBox;
                Label lblCount = e.Row.FindControl("lblCount") as Label;
                HtmlInputCheckBox chk = (HtmlInputCheckBox)e.Row.FindControl("checkbox1");
                //if (ltlOrderDetailState.Text == "0")
                //{
                //    ltlOrderDetailState.Text = "未提交";
                //}
                //else if (ltlOrderDetailState.Text == "1")
                //{
                //    ltlOrderDetailState.Text = "已提交";
                //}
                //else if (ltlOrderDetailState.Text == "2")
                //{
                //    ltlOrderDetailState.Text = "已确认";
                //}
                //else if (ltlOrderDetailState.Text == "3")
                //{
                //    ltlOrderDetailState.Text = "拒绝配送";
                //}

                if (ViewState["status"].ToString() == "1")
                {
                    txtCount.Visible = false;
                    lblCount.Visible = true;
                }
                else
                {
                    txtCount.Visible = true;
                    lblCount.Visible = false;
                }
            }
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    if (ddlProjectid.SelectedItem.Value == "0002")
                    {
                        e.Row.Cells[2].Text = "自主报价";
                    }
                    else
                    {
                        e.Row.Cells[2].Text = "采购限价";
                    }
                }
            }
        }

        /// <summary>
        /// 提交采购单（没有采购单明细时，无法提交采购单）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ////无采购明细，无法提交采购单
            //if (gvwPurchaseOrderDetail.Rows.Count <= 0)
            //{
            //    HZ.Web.WebUtil.Alert("还未采购任何明细，无法提交采购单！");
            //    return;
            //}

            //无采购明细，无法提交采购单
            if (gvwPurchaseOrderDetail.Rows.Count <= 0)
            {
                HZ.Web.WebUtil.Alert("还未采购任何明细，无法提交采购单！");
                return;
            }

            //还未采购任何明细，无法提交采购单！
            if (string.IsNullOrEmpty(txtAmount.Text.Trim()))
            {
                HZ.Web.WebUtil.Alert("还未采购任何明细，无法提交采购单！", this);
                return;
            }
            //输入的采购总金额为非法字符
            if ((new HZ.Common.ConvertHelper(txtAmount.Text.Trim()).ToFloat) == null)
            {
                HZ.Web.WebUtil.Alert("采购总金额为非法字符！", this);
                return;
            }

            //还未正确添加采购任何明细，无法提交采购单！
            if ((new HZ.Common.ConvertHelper(txtAmount.Text.Trim()).ToInt32) == 0)
            {
                HZ.Web.WebUtil.Alert("还未正确添加采购任何明细，无法提交采购单！", this);
                return;
            }


            ////无采购明细，无法提交采购单
            //if (gvwPurchaseOrderDetail.Rows.Count <= 0)
            //{
            //    HZ.Web.WebUtil.Alert("还未采购任何明细，无法提交采购单！");
            //    return;
            //}
            //采购单明细的采购数量有空的，无法提交采购单
            for (int i = 0; i < gvwPurchaseOrderDetail.Rows.Count; i++)
            {
                TextBox txtPurchaseCount = (TextBox)gvwPurchaseOrderDetail.Rows[i].FindControl("txtCount");
                if (string.IsNullOrEmpty(txtPurchaseCount.Text))
                {
                    HZ.Web.WebUtil.Alert("有采购量为空的明细，无法提交采购单！", this);
                    txtPurchaseCount.Focus();
                    return;
                }
            }
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            purchaseOrder.OrderID = Request.QueryString["OrderID"];
            int state = ip.UpdatePurchaseOrderDetail_Submit(purchaseOrder);
            if (state == 1)
            {
                PageInfo("采购单提交成功！", "PurchaseOrderCheck.aspx");
            }
            else if (state == 2)
            {
                PageInfo("采购单已提交或已删除！", "PurchaseOrderCheck.aspx");
            }
            else
            {
                PageError("提交失败！", "PurchaseOrderUnCheck.aspx");
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            SetAllBind();
        }

        /// <summary>
        /// 删除采购单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelOrder_Click(object sender, EventArgs e)
        {
            PurchaseOrder dPurchaseOrder = new PurchaseOrder();
            dPurchaseOrder.OrderID = Request.QueryString["OrderID"];
            int state = ip.DeletePurchaseOrder(dPurchaseOrder);
            if (state == 1)
            {
                PageInfo("采购单删除成功！", "PurchaseOrderUnCheck.aspx");
            }
            else if (state == 2)
            {
                PageInfo("采购单已提交或已删除！", "PurchaseOrderUnCheck.aspx");
            }
            else
            {
                PageError("删除失败！", "");
            }
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            string orderId = Request.QueryString["OrderID"];
            Model.Query.PurchaseOrderDetail qPurchaseOrderDetail = new HZ.DrugTrade.Model.Query.PurchaseOrderDetail();
            qPurchaseOrderDetail.OrderID = orderId;
            qPurchaseOrderDetail.GoodsName = txtGoodsName.Text.Trim();
            qPurchaseOrderDetail.Outlookc = txtOutLookc.Text.Trim();
            //qPurchaseOrderDetail.PinyinCode = this.txtPinyinCode.Text.Trim();
            qPurchaseOrderDetail.CompanyName_SC = txtCompany_SC.Text.Trim();
            qPurchaseOrderDetail.PinyinCode = this.txtpinyincode.Text.Trim();
            qPurchaseOrderDetail.CompanyName_PS = txtCompany_PS.Text.Trim();
            qPurchaseOrderDetail.Unit = txtUnit.Text.Trim();
            //qPurchaseOrderDetail.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                qPurchaseOrderDetail.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                qPurchaseOrderDetail.ProjectID = "0001";
            }
            //if (!string.IsNullOrEmpty(txtPriceFrom.Text.Trim()))
            //{
            //    qPurchaseOrderDetail.PriceFrom = Convert.ToDecimal(txtPriceFrom.Text.Trim());
            //}
            //if (!string.IsNullOrEmpty(txtPriceTo.Text.Trim()))
            //{
            //    qPurchaseOrderDetail.PriceTo = Convert.ToDecimal(txtPriceTo.Text.Trim());
            //}
            qPurchaseOrderDetail.SortFields = "PlanTime DESC";
            int totalCount = 0;
            IList<Model.View.PurchaseOrderDetail> purchaseOrderDetailList = ip.GetPurchaseOrderDetailByWhere(qPurchaseOrderDetail, 1, 0, out totalCount);
            DataTable dt = HZ.Data.ModelConvert.GetDataTableFromModel(purchaseOrderDetailList);
            //执行导出
            HZ.Excel.ExcelHelper.ExportDataForWeb(dt, gvwPurchaseOrderDetail);

        }

        protected void btnDrop_Click(object sender, EventArgs e)
        {
            string orderId = Request.QueryString["OrderID"];
            Model.Query.PurchaseOrderDetail qPurchaseOrderDetail = new HZ.DrugTrade.Model.Query.PurchaseOrderDetail();
            Model.PurchaseOrder orderlist = new Model.PurchaseOrder();
            orderlist.OrderID = orderId;
            qPurchaseOrderDetail.OrderID = orderId;

            qPurchaseOrderDetail.SortFields = "executetime asc";

            int totalCount = 0;
            IList<Model.View.PurchaseOrderDetail> purchaseOrderDetailList = ip.GetPurchaseOrderDetailByWhere(qPurchaseOrderDetail, 1, 0, out totalCount);
            if (purchaseOrderDetailList.Count > 0)
            {
                //    if (purchaseOrderDetailList[0].OrderDetailState == 2)
                //    {
                //        HZ.Web.WebUtil.Alert("已确认配送的订单不能撤回！");
                //        SetAllBind();
                //    }
                //    else if (purchaseOrderDetailList[0].OrderDetailState == 1)
                //    {
                int state = ip.DropPurchaseOrder(orderlist);
                if (state == 1)
                {
                    PageInfo("采购单撤回成功！", "PurchaseOrderUnCheck.aspx");
                    SetAllBind();
                }
                else if (state == 2)
                {
                    PageInfo("已确认配送的订单不能撤回！", "PurchaseOrderUnCheck.aspx");
                    SetAllBind();
                }
                else
                {
                    PageError("撤回失败！", "");
                    SetAllBind();
                }
                //}
                //else
                //{
                //    HZ.Web.WebUtil.Alert("该采购单还未提交！");
                //    SetAllBind();
                //}
            }
            else
            {
                PageInfo("采购单已经被删除无法撤回！", "PurchaseOrderUnCheck.aspx");
            }

        }
    }
}
